

<script>
import {getZFormFieldComDef} from "./render";

function tagName(name) {
  return ZY.lodash.upperFirst(ZY.lodash.camelCase(name));
}

export let baseZFormComMixin = {
  inject: [
      'curFormCon',
    'ZCurFieldIns',
  ],
  computed: {
    zfield__listeners: function () {
      var vm = this
      // console.log(vm)
      // `Object.assign` 将所有的对象合并为一个新对象
      return Object.assign({},
          // 我们从父级添加所有的监听器
          this.$listeners,
          // 然后我们添加自定义监听器，
          // 或覆写一些监听器的行为
          {
            // 这里确保组件配合 `v-model` 的工作
            // blur: function (event) {
            //   // console.log('eveev', event)
            //   vm.zfield__emit('com:blur', {
            //
            //   }, event)
            // },
            // focus: function (event) {
            //   // console.log('eveev', event)
            //   vm.zfield__emit('com:focus', {
            //
            //   }, event)
            // },
            // input: function (event) {
            //   // console.log(event)
            //   vm.$emit('input', event.target.value)
            // }
          }
      )
    },
    zfield__readonly() {
      let readonly = this.zfield__globalUIConfig?.globals?.readonly
      if (readonly) {
        return true
      }
    },
    zfield__disabled() {
      let disabled = this.zfield__globalUIConfig?.globals?.disabled
      if (disabled) {
        return true
      }
    },
  },
  methods: {
    zfield__req(zFormMeta, {event = '', options = {api: ''}} ={}) {
      return new Promise(async (resolve) => {
        let request =  zFormMeta?.request
        if (request && request[event]) {

          let [err, res] = await  ZY.awaitTo(request[event](options))
          if (err) {
            console.log('zfield__req err', err)
          } else {
            console.log('zfield__req', res)
            resolve(res)
          }

        }
      })
    },
    zfield__setVal(v) {
      this.value = v
    },
    zfield__setAndUpdate(v) {
      this.zfield__setVal(v)
      this.zfield__onInput(v)
    },
    zfield__onInput(v) {
      this.zfield__emit('com:input', {
        value: v
      })
      // console.log('sdsdsdsdsds', v)
      this.$emit('change', v)
      if (this.ZCurFieldIns) {
        this.ZCurFieldIns.input(v)
      }
    },
    zfield__emit(name, v = {}, originEvent) {
      if (v) {
        v.self_path = this.zfield__outerProps?.self_path
        v.config =  this.zfield__propConfig
        v.ctx = this
        v.curFormCon = this.curFormCon
        v.props = this.zfield__outerProps
        v.pathArr = this.zfield__outerProps?.pathArr
      }
      if (this.curFormCon) {
        this.curFormCon.listenEvent(name, v, originEvent)
      }
    },
    async zfield__initDataSource({onRequest, lazyLoad} = {}) {
      let optionsUrl = ZY.lodash.get(this.ui, 'widgetConfig.optionsUrl')
      let optionsWidgetConfig = ZY.lodash.get(this.ui, 'widgetConfig') ?? {}
      let optionsUI = this.ui ?? {}

      // console.log(optionsUrl)
      if (lazyLoad) {
        return;
      }

      if (optionsUI.enableRemote && onRequest) {
        await  onRequest({ config: optionsWidgetConfig, url: '', ui: optionsUI}, {type: 'options', ui: this.ui, ctx: this})
        return;
      }

      if (optionsUrl  && onRequest) {
        await  onRequest({ config: optionsWidgetConfig, url: optionsUrl, ui: optionsUI}, {type: 'options', ui: this.ui, ctx: this})

        return;
      }
    },
    zfeild__buildOptions(ui, optArr) {
      let _widget = ZY.lodash.get(ui, ['widgetConfig']) ?? {}
      let source = ZY.lodash.get(ui, ['source'])
      let options = []
      if (_widget.options) {
        try {
          let opt = _widget.options
          options = options.concat(opt)
        } catch (e) {
          //
        }
      }
      if (_widget.options2) {
        try {
          let opt = ZY.JSON5.parse(_widget.options2)
          options = options.concat(opt)
        } catch (e) {
          //
        }
      }
      if (_widget.tree_options) {
        try {
          let opt = ZY.JSON5.parse(_widget.tree_options)
          options = options.concat(opt)
          // console.log(options)
        } catch (e) {
          //
        }
      }

      if (source) {
        try {
          let opt = ZY.JSON5.parse(source)
          let data = opt.data
          // options = options.concat(opt)
          if (data.type === 'STATIC') {
            let cur = data.obj[data.type]
            if (cur.value) {
              let opt = ZY.JSON5.parse(cur.value)

              // console.log('buildOptions', opt)
              options = options.concat(opt)
            }
          }
        } catch (e) {
          //
        }
      }
      if (optArr) {
        options = options.concat(optArr)
      }
      // console.log(_widget, widgetConfig2)
      return options
    }
  }
}



export default {
  name: 'ZSingleField',
  props: {
    config: {
      type: Object,
      default() {
        return {}
      }
    },
    value: null
  },
  provide() {
    let self = this
    return {
      ZCurFieldIns: {
        input(v) {
          self.$emit('input', v)
          // self.$emit('change', v)
        }
      }
    }
  },
  setup(props) {
    let h = vueCompositionAPI.h
    // let fieldMixinDefMap = getFieldMixinDefMap()
    let tag = ZY.lodash.get(props.config, '__config__.tag');
    console.log('rerender', tag, props.value, props.config)
    let defName = tagName(tag ? tag : '');
    let defFun = getZFormFieldComDef(defName);
    let def = defFun.create({
      ui: {
        tag,
        widgetConfig: {
          ...props.config,
          ...props.config.__config__
        }
      }
    }, {
      value: props.value
    })
    if (!def.mixins) {
      def.mixins = []
    }
    def.mixins.push(baseZFormComMixin)



    return () => {
      return h(def)
    }
  }
}
</script>
